package com.jsy.fille.util;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FastDFSClient {
    public static void main(String[] args) throws IOException, MyException {
        //读取文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\me\\ppt\\63.jpg");
        byte[] bytes = Files.readAllBytes(Paths.get(file.getPath()));
        String url = upload(bytes, "jpg");
        System.out.println(url);
        delete("group1", "M00/00/00/wKgMqF37QvSAX8wtAACH8MULczg18.jpg");
    }

    /**
     * 上传文件到fastDFS并返回可访问地址
     *
     * @param bytes       文件字节数组
     * @param fileExtName 文件扩展名
     * @return 文件可访问地址
     */
    public static String upload(byte[] bytes, String fileExtName) throws IOException, MyException {
        //通过文件名和扩展名拼接url
        String url = "";
        //获取存储客户端
        StorageClient storageClient = getStorageClient();
        /*
        上传文件
        参数1：文件字节数组
        参数2：拓展名
        参数3：文件meta信息，如作者，创建时间
        返回值：返回一个字符串数组 包含组名和文件名
        如group1   /M00/00/00/wKgMqF37QvSAX8wtAACH8MULczg18.jpg
         */
        String[] uploadFile = storageClient.upload_file(bytes, fileExtName, null);
//        System.out.println(uploadFile);
        //获取动态存储服务器ip
        FileInfo fileInfo = storageClient.get_file_info(uploadFile[0], uploadFile[1]);
        //url="http://192.168.12.168/group1/M00/00/00/wKgMqF37QvSAX8wtAACH8MULczg18.jpg"
        url = "http://" + fileInfo.getSourceIpAddr() + "/" + uploadFile[0] + "/" + uploadFile[1];
        return url;
    }

    public static void delete(String groupName, String remoteFileName) throws IOException, MyException {
        StorageClient storageClient = getStorageClient();
        storageClient.delete_file(groupName, remoteFileName);
    }

    /**
     * 通过配置文件获取fdfs客户端
     *
     * @return
     * @throws IOException
     * @throws MyException
     */
    private static StorageClient getStorageClient() throws IOException, MyException {
        //获取配置文件路径
        String confPath = new ClassPathResource("fdfs_client.conf").getPath();
        //设置配置信息
        ClientGlobal.init(confPath);
        //创建追踪服务器
        TrackerClient trackerClient = new TrackerClient();
        //创建存储服务器客户端
        TrackerServer trackerServer = trackerClient.getConnection();
        return new StorageClient(trackerServer, null);
    }

}
